<?php



// check user login
session_start();
if (isset($_SESSION["user"]) && !empty($_SESSION["user"])) {
//echo $_SESSION["user"];

//include 'function_library.php';


class Turn extends CI_Controller {

	public function __construct() {
            parent::__construct(); 

            $this->load->helper(array('form','url'));
            //$this->load->library('form_validation');
	}
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function index() {
           
        echo form_open('turn/run_turn');
        echo form_submit('submit','Run Turn!');
        echo form_close();
            
        } /// end function index
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function run_turn() {
            
            $time_start = microtime(true);
            
           
               
             $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
             $current_turn = $turndata->getTurnNumber();  
             
             //$current_turn = $query->getTurnNumber();
             
             $new_turn = $current_turn + 1;
             echo "<br>It was turn " . $current_turn . " and is now turn " .$new_turn . "</br>";
             
             $turndata->setTurnNumber($new_turn);
             $this->doctrine->em->persist($turndata);
             $this->doctrine->em->flush();
             
             ////////////////////////////////////////////////////////////////////////////////////////////////
             ////////// do AI stuff
             
             $this->check_pending_claims();
             
             $this->title_updates();
             
             // consider wedding proposals
             $this->AI_consider_proposals();
             
             // marry off children
             $this->AI_marry_off_daughters();
             
             // seek spouse, if single
             $this->AI_seek_spouse();
             
             $this->conduct_warfare();
             
             $this->check_war_status();
             
             // enforce claim on other titles
             $this->AI_claim_war();
              
              // claim other titles
             $this->AI_claim_title_v2();
             
             $this->title_updates();
             
             // plot
             
              //////////////// end AI stuff
             ////////////////////////////////////////////////////////////////////////////////////////////////
              
             //maybe check deaths first, and exclude pregnant women from death checks since they have their own?
             $this->get_pregnant();
             //$this->check_deaths();
             $this->gestation();
            
             // warfare
             
             
             // prestige gain/decline
             
             
             // perform weddings
             $this->perform_weddings();
             
             
             $this->region_levies_replenish();
             
             // money
             //$this->money_income();
             $time_start_local = microtime(true);
             
             $this->tax_income();
             
             $time_end_local = microtime(true);
             $time = $time_end_local - $time_start_local;
             //echo "<br>Load Time:  " . round($time, 3) . " seconds\n";
             
             
             $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($new_turn);
                $logmsg -> setText("Tax income section of TurnRun took " . round($time, 3) . " seconds");
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('3');
                $this->doctrine->em->persist($logmsg);
             $this->doctrine->em->flush();
             
             // deaths
            
             
             //$this->doctrine->em->flush();
            
             
            $time_end = microtime(true);
            $time = $time_end - $time_start;
            //echo "<br>Load Time:  " . round($time, 3) . " seconds\n";
            $logmsg = new ORM\Dynasties2\Gamelog;
            $logmsg -> setOnTurn($new_turn);
            $logmsg -> setText("Turn run, took " . round($time, 3) . " seconds");
            $logmsg -> setTimeStamp(new DateTime());
            $logmsg -> setMsgType('3');
            $this->doctrine->em->persist($logmsg);
            $this->doctrine->em->flush();
        } /// end function run_turn
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function run_10_turns() {
            
            $i = '10';
            
            while ($i > '0') {
                
                $this->run_turn();
                
                $i--;
            }
            
        }/// end function run_10_turns
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function run_20_turns() {
            
            $i = '20';
            
            while ($i > '0') {
                
                $this->run_turn();
                
                $i--;
            }
            
        }/// end function run_10_turns
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        public function get_pregnant() {
            // checks married non-pregnant females of suitable age for pregnancy
            //echo "</br>Pregnancy checks.</br>";
            // determine age variable so you don't have 90 year old pregnant women
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
             $current_turn = $turndata->getTurnNumber();  
            // cut off age will be 45 years old, which is 360 turns.
            $cut_off = $current_turn - 360;
            //echo $cut_off;
                                    
            $query = $this->doctrine->em->createQuery("select u 
                    from ORM\Dynasties2\Characters u 
                    WHERE u.marriedDate IS NULL
                        AND u.deathDate IS NULL
                        AND u.isFemale = '1' 
                        AND (u.isPregnant IS NULL 
                            OR u.isPregnant = '0') 
                        AND u.bornDate < $cut_off ");
            
            $eligible_women = $query->getResult();
            
            //\Doctrine\Common\Util\Debug::dump($eligible_women);
            
            // insert the father's charID into isPregnant so that it will easily get to the baby even if dad dies during pregnancy
            
            
        } /// end public function get_pregnant()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        public function title_updates() {
            
            
            
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
             $current_turn = $turndata->getTurnNumber();  
             
            $this->load->helper('dynasties2_common');
            //see if anyone is a triple count
            
            $query = $this->doctrine->em->createQuery("
                SELECT u
                FROM ORM\Dynasties2\Titles u
                ");
            $titles = $query -> getResult();
            
            $allcharacters = array();
            
            foreach ($titles as $row) {
                
                $char_id = $row->getCharacterLink()->getId();
                
                if (array_key_exists($char_id, $allcharacters)) {
                    //echo "<br>Hit on in_array!</br>";
                    $val = $allcharacters[$char_id];
                    $val++;
                    //echo "<br>$val";
                    $allcharacters[$char_id] = $val;
                    
                } else {
                    //echo "<br>pass</br>";
                    $allcharacters[$char_id] = '1';
                }
                
                
            } // end foreach titles as row
            
            //print_r($allcharacters);
            foreach ($allcharacters as $key => $row) {
                
                //echo "<br>" . $key . ", " . $row;
                if ($row > '2') {
                    echo "<br>" . $key . " has more than two regions and needs to do something with them.";
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Character $key has more than two regions.");
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('3');
                    $this->doctrine->em->persist($logmsg);
                    $this->doctrine->em->flush();
                    
                    $character_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $key);
                    $is_AI = $character_data->getUseAi();
                    
                    $rand = rand(1,2);
                    if ($rand > '0' AND $is_AI == '1') {  // simplified - will always choose to create a vassal
                        
                        // already has a duchy?
                        //$char_id = $row->getId();
                        $char_id = $row;
                        $has_duchy = $this->doctrine->em->getRepository('ORM\Dynasties2\Duchies')->findOneBy(array('characterLink' => $key));
                        if ($has_duchy) {
                            // has duchy
                            echo "<br>test, has duchy.";
                            
                        } else {
                            // does not have duchy
                            //echo "<br>test, does not have duchy.";
                            
                            // create a duchy
                        
                        $characterdata = $this->doctrine->em->find('ORM\Dynasties2\Characters', $key);
                        $charname = $characterdata->getCharacterName();
                        $duchyname = "Duchy of " . $charname;
                        
                        $char_prestige = $characterdata->getPrestige();
                        $char_prestige = $char_prestige + '100';
                        $characterdata->setPrestige($char_prestige);
                        
                        $new_duchy = new ORM\Dynasties2\Duchies;
                        $new_duchy->setDuchyName($duchyname);
                        $new_duchy->setCharacterLink($characterdata);
                        $this->doctrine->em->persist($new_duchy);
                        $this->doctrine->em->flush();
                        
                        $regions = get_a_rulers_regions($key);
                        //print_r($regions);
                        foreach ($regions as $row) {
                            $new_duchy_region = new ORM\Dynasties2\Duchyregions;
                            $new_duchy_region->setWhichDuchy($new_duchy->getId());
                            $new_duchy_region->setWhichRegion($row);
                            $this->doctrine->em->persist($new_duchy_region);
                        }
                        $this->doctrine->em->flush();
                            
                            
                        } //// end DOES NOT HAVE DUCHY and corresponding code to create a duchy
                        
                        
                        // give a county to another - who will become a vassal!
                        // which county? pick at random I suppose
                        $regions = get_a_rulers_regions($key);
                        //print_r($regions);
                        $key2 = array_rand($regions);
                        $region_to_give = $regions[$key2];
                        
                        // who to give it to?
                        // does he have an adult male child?
                        $of_age = $current_turn - 128;
                        $query = $this->doctrine->em->createQuery("
                            SELECT u
                            FROM ORM\Dynasties2\Characters u
                            WHERE u.fathersId = $key
                                AND u.deathDate IS NULL
                                AND u.isRuler = '0' 
                                AND u.isFemale = '0'
                                AND u.useAI = '1'
                                AND u.bornDate <= $of_age
                            ");
                        //$query->setMaxResults(1);
                        $sons_of_age = $query -> getResult();
                        
                        $character_data = array();
                        
                        // should check to make sure none of them are already landed
                        if ($sons_of_age) {
                            
                            echo "<br>Does have at least one son of age. Code this.";
                            
                            
                            
                            $logmsg = new ORM\Dynasties2\Gamelog;
                            $logmsg -> setOnTurn($current_turn);
                            $logmsg -> setText("Testing of vassal creation code: does have a son of age! more code is needed.");
                            $logmsg -> setTimeStamp(new DateTime());
                            $logmsg -> setMsgType('3');
                            $this->doctrine->em->persist($logmsg);
                            $this->doctrine->em->flush();
                            
                            foreach ($sons_of_age as $row) {
                                /// this is a bandaid fix - it will give the youngest eligible son the title.
                                $new_vassal = $this->doctrine->em->find('ORM\Dynasties2\Characters', $row->getId());
                            }
                            
                            
                        } else {
                            echo "<br>No sons of age.";
                            // create a vassal!
                            
                            $character_data['name'] = generate_male_name();
                            
                            $status_rand = rand(1,4);
                            // 1 = young and unmarried
                            // 2 = young and married
                            // 3 = older and unmarried
                            // 4 = older and married
                            // for now, skipping it though, for simplicity
                            $age_rand = mt_rand(136,192);
                            $born_turn = $current_turn - $age_rand;
                            $prestige_val = '10';
                            
                            
                            $character_data['bornturn'] = $born_turn;
                            $character_data['isfemale'] = '0';
                            $character_data['playercontrolled'] = '0';
                            $character_data['useai'] = '1';
                            $character_data['isruler'] = '1';
                            $character_data['fathersID'] = '0';
                            $character_data['mothersID'] = '0';
                            $character_data['prestige'] = $prestige_val;
                            $character_data['ambition'] = tendten();
                            $character_data['leadership'] = tendten();
                            $character_data['money'] = '100';
                            $character_data['diplomacy'] =  tendten();
                            $character_data['marriedto'] = NULL;
                            $character_data['marriedturn'] = NULL;
                            $character_data['whichfamily'] = '0';
                            
                            $this->load->model('setup_data_model'); 
                            $char_id = $this->setup_data_model->commit_new_character_to_db_v2($character_data); 
                            
                            $logmsg = new ORM\Dynasties2\Gamelog;
                            $logmsg -> setOnTurn($current_turn);
                            $logmsg -> setText("Character $key gave a region to a newly created vassal, $char_id. Region id: $region_to_give, another message should follow.");
                            $logmsg -> setTimeStamp(new DateTime());
                            $logmsg -> setMsgType('3');
                            $this->doctrine->em->persist($logmsg);
                            $this->doctrine->em->flush();
                            $new_vassal = $this->doctrine->em->find('ORM\Dynasties2\Characters', $char_id);
                            ////////////////////////////                            
                            }   //// else for when there's no eligible son to pass a title to
                            
                            echo "<br>troubleshooting:  ";
                            echo $new_vassal->getCharacterName();
                            echo "<br>";
                            
                        $title_data = $this->doctrine->em->getRepository('ORM\Dynasties2\Titles')->findOneBy(array('regionLink' => $region_to_give));
                        $title_id = $title_data->getId();
                        $title_data->setCharacterLink($new_vassal);
                        $title_data->setVassalTo($key);
                        $this->doctrine->em->persist($title_data);
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Char $key gave region $region_to_give to $char_id, title: $title_id");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('3');
                        $this->doctrine->em->persist($logmsg);
                            //$this->doctrine->em->flush();

                        $this->doctrine->em->flush();
                        
                        
                    } /// rand decision logic to see if AI will form a duchy
                    
                } /// if row check for 2+ titles in their name
                
            } /// end of foreach allcharacters array, checks to see if anyone has 2+ titles in their name
            
            /////////////////////////////////////////////
            // now lets see if any duchies have been reduced to fewer than 3 regions
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Duchyregions u 
                    ");
            
            $duchydata = $query->getResult();
            
            $duchy_counting = array();
            foreach ($duchydata as $row) {
                if (isset($duchy_counting[$row->getWhichDuchy()])) {
                    $duchy_counting[$row->getWhichDuchy()] = $duchy_counting[$row->getWhichDuchy()] + 1;
                } else {
                     $duchy_counting[$row->getWhichDuchy()] = '1';
                }
            }
            //print_r($duchy_counting);
            foreach ($duchy_counting as $key => $row) {
                if ($row < '3') {
                    //echo "<br>Got a hit on $key.";
                    $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Duchyregions u 
                        WHERE u.whichDuchy = $key
                    ");
                    $duchyregion_data = $query->getResult();
                    foreach ($duchyregion_data as $row) {
                        //echo $row->getId();
                       $this->doctrine->em->remove($row); 
                    }
                    $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Duchies u 
                        WHERE u.id = $key
                    ");
                    $duchy_data = $query->getResult();
                    //echo $duchy_data->getDuchyName();
                    
                    foreach ($duchy_data as $row) {
                        
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("A Duchy is destroyed: " . $row->getId() . ", char " . $row->getCharacterLink()->getId() . ", after it was reduced to fewer than 3 regions.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('3');
                        $this->doctrine->em->persist($logmsg);
                        
                        $char_prestige = $row->getCharacterLink()->getPrestige();
                        $char_prestige = $char_prestige - '100';
                        $row->getCharacterLink()->setPrestige($char_prestige);
                        $this->doctrine->em->remove($row); 
                        
                    }
                    
                    
                } /// end if row < 3
            } /// end foreach duchy counting to remove offending duchies
            $this->doctrine->em->flush();
            
            
        }/// end public function title_updates()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        
        public function perform_weddings() {
             
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Betrothals u 
                    WHERE u.onTurn = $current_turn
                        ");
            
            $weddings = $query->getResult();
            
            echo "<br>-------Weddings----------------------------------------------------";
            
            foreach ($weddings as $row) {
                
                echo "<br>Lets Marry " . $row->getBrideId() . " and " . $row->getGroomId() . ".";
                
                $bride_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $row->getBrideId());
                $groom_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $row->getGroomId());
                
                $bride_data->setWhichFamily($groom_data->getWhichFamily());
                $bride_data->setMarriedTo($groom_data->getId());
                $bride_data->setMarriedDate($current_turn);
                $bride_data->setMarriageCode(NULL);
                $bride_data->setMarriedOutOfFamily($bride_data->getWhichFamily());
                
                $groom_data->setMarriedTo($bride_data->getId());
                $groom_data->setMarriedDate($current_turn);
                $groom_data->setMarriageCode(NULL);
                
                
                $this->doctrine->em->persist($bride_data);
                $this->doctrine->em->persist($groom_data);
                $this->doctrine->em->flush();
                
                
            } // end the foreach
            
            
        } /// end public function perform_weddings()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        public function AI_consider_proposals() {
        
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE (u.deathDate IS NULL)
                        AND u.isRuler = '1'
                        AND u.useAI = '1'
                        ");
            
            $rulers = $query->getResult();
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Proposals u
                        ");
            
            $proposals = $query->getResult();
            echo "<br>-------Proposal considerations-------------------------------------";
            foreach ($proposals as $row) {
                //echo "<br>Proposal from " . $row->getCharacter2()->getWhichFamily();
                //echo "<br>Proposal from " . $row->getFromFamily();
                $rand = mt_rand(1,2);
                $proposal_id = $row->getId();
                $bride = $row->getCharacter1()->getId();
                $bride_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $bride);
                if ($rand == '1') {
                    // accept
                    
                    $groom = $row->getCharacter2()->getId();
                    $turn = $row->getTargetTurn();
                    
                    $groom_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $groom);
                    
                    $new_betrothal = new ORM\Dynasties2\Betrothals;
                    $new_betrothal->setBrideId($bride);
                    $new_betrothal->setGroomId($groom);
                    $new_betrothal->setOnTurn($turn);
                    $new_betrothal->setIsMatrilineal('0');

                    $this->doctrine->em->persist($new_betrothal);
                    
                    $groom_data->setMarriageCode('2');
                    $bride_data->setMarriageCode('2');
                    $this->doctrine->em->persist($bride_data);
                    $this->doctrine->em->persist($groom_data);
                    
                    echo "<br>Proposal accepted (new betrothal).";
                } else {
                    // reject
                    // send a message perhaps
                    $bride_data->setMarriageCode(NULL);
                    $this->doctrine->em->persist($bride_data);
                    echo "<br>Proposal rejected.";
                }
                $this->doctrine->em->remove($row);
                $this->doctrine->em->flush();
                
            }
            
        } /// end public function AI_consider_proposals()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        
        
        public function AI_marry_off_daughters() {
            
            echo "<br>-------Wedding proposals-------------------------------------------";
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            $marriable_age = $current_turn - 128;
        
            // this query selects all living AI rulers
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE (u.deathDate IS NULL)
                        AND u.isRuler = '1'
                        AND u.useAI = '1'
                        ");
            
            $potential_bride_dads = $query->getResult();
            foreach ($potential_bride_dads as $row) {
                
                $fatherid = $row -> getId();
                $father_diplomacy = $row->getDiplomacy();
                //echo "<br>dad diplomacy: " . $father_diplomacy . ".</br>";
                
                //echo $row ->getId();
                
                // checks to see if the ruler has any marriable daughters
                $query2 = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE u.marriedDate IS NULL
                        AND u.deathDate IS NULL
                        AND u.marriageCode IS NULL
                        AND u.fathersId = $fatherid
                        AND u.isRuler = '0' 
                        AND u.isFemale = '1'
                        AND u.useAI = '1'
                        AND u.bornDate <= $marriable_age
                        ");
            
                $eligible_daughters = $query2->getResult();
                
                //echo "<br>";
                ////print_r($eligible_daughters);
                foreach ($eligible_daughters as $row2) {
                    
                    //echo "*** test ** " . $row2->getFathersId() . " ***</br>";
                    
                    /// build the array:
                    $fatherdaughter_array[] = $fatherid;
                    
                    
                }
                
                
            } // end foreach $potential_bride_dads
            
            
            if (isset($fatherdaughter_array)) {
                //echo "<br>fatherdaughterarray is good!</br>";
                $result = array_unique($fatherdaughter_array);
             foreach ($result as $row) {
                 
                    $data['father_id'] = $row;
                    $father = $this->doctrine->em->find('ORM\Dynasties2\Characters', $row);
                    //echo $row;
                    if ($father->getDiplomacy() > '0') {
                        //echo "woozah";

                        $marriage_rand = mt_rand(1,5);

                        if ($father->getDiplomacy() < '26') {
                            if ($marriage_rand > '4') {
                                //echo "<br>A wedding!1 - " . $father->getId() . "</br>";
                                $this->AI_select_daughter_and_husband($data);
                            } //else echo "<br>No wedding1.</br>";
                        } elseif ($father->getDiplomacy() < '51') {
                            if ($marriage_rand > '3') {
                                //echo "<br>A wedding!2 - " . $father->getId() . "</br>";
                                $this->AI_select_daughter_and_husband($data);
                            } //else echo "<br>No wedding2.</br>";

                        } elseif ($father->getDiplomacy() < '76') {
                            if ($marriage_rand > '2') {
                                //echo "<br>A wedding!3 - " . $father->getId() . "</br>";

                                $this->AI_select_daughter_and_husband($data);

                            } //else echo "<br>No wedding3.</br>";

                        } elseif ($father->getDiplomacy() < '101') {
                            if ($marriage_rand > '1') {
                                //echo "<br>A wedding!4 - " . $father->getId() . "</br>";
                                $this->AI_select_daughter_and_husband($data);
                                // figure out which daughter to marry off, and whom to marry her to.
                                // how many eligible daughters?

                                $query2 = $this->doctrine->em->createQuery("SELECT u 
                                        FROM ORM\Dynasties2\Characters u 
                                        WHERE (u.marriedDate IS NULL)
                                            AND (u.deathDate IS NULL)
                                            AND u.marriageCode IS NULL
                                            AND u.fathersId = $row
                                            AND u.isRuler = '0' 
                                            AND u.isFemale = '1'
                                            AND u.useAI = '1'
                                            AND u.bornDate <= $marriable_age
                                        ");

                                $eligible_daughters = $query2->getResult();

                            } //else echo "<br>No wedding4.</br>";

                        } /// end the last diplomacy ifelse

                    } /// end diplomacy checks

                } /// end foreach result as row
                
                
            } else {
                $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($current_turn);
                $logmsg -> setText("No marriable daughters left in the game.");
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('3');
                $this->doctrine->em->persist($logmsg);
                $this->doctrine->em->flush();
                //echo "<br><b>no such thing as fatherdaughterarray!!!! Appears fatherID $fatherid has no unmarried daughters.</b></br>";
            }
            
            
             
            
        } /// end public function AI_marry_off_daughters2()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function AI_select_daughter_and_husband($data) {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            $marriable_age = $current_turn - 128;
            $father_id = $data['father_id'];
            //$count = $data['count'];
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE (u.marriedDate IS NULL)
                        AND (u.deathDate IS NULL)
                        AND u.marriageCode IS NULL
                        AND u.isFemale = '0'
                        AND u.useAI = '1'
                        AND u.bornDate <= $marriable_age
                        ");
            //echo "<br>Test: eligible husbands:</br>";
            
            $eligible_husbands = $query->getResult();
            //print_r($eligible_husbands);
            $husbands_count = count($eligible_husbands) - 1;
            //$data['count'] = $husbands_count;
            foreach ($eligible_husbands as $row) {
                if ($row->getIsRuler() == '1') {
                    $pre = "<b>";
                    $post = "*</b>";
                } else {
                    $pre = "";
                    $post = "";
                }
                //echo $row->getCharacterName();
                $years_old = ($current_turn - $row->getBornDate()) / 8;
                //echo $pre . $row->getCharacterName() . " ($years_old)[" . $row->getPrestige() . "]" . $post . ", ";
                
             }
            
            $query2 = $this->doctrine->em->createQuery("SELECT u 
                        FROM ORM\Dynasties2\Characters u 
                        WHERE u.marriedDate IS NULL
                            AND u.deathDate IS NULL
                            AND u.marriageCode IS NULL
                            AND u.fathersId = $father_id
                            AND u.isRuler = '0' 
                            AND u.isFemale = '1'
                            AND u.useAI = '1'
                            AND u.bornDate <= $marriable_age
                            ");

                    $eligible_daughters = $query2->getResult();
                    //echo count($eligible_daughters);
                    //print_r($eligible_daughters[0]);
                    $daughter_count = count($eligible_daughters);

                    if ($daughter_count == '1') {
                       
                        $daughter_name = $eligible_daughters[0]->getCharacterName();
                        $daughter_id = $eligible_daughters[0]->getId();
                        $daughter_fam = $eligible_daughters[0]->getWhichFamily();


                    } elseif ($daughter_count == '2') {
                        $rand = mt_rand(1,3);
                        if ($rand < '3') {
                            // marry off the eldest,
                            //echo "<br>Marry off an eldest: ";
                            //echo $eligible_daughters[0]->getCharacterName();
                            //echo ", ";
                            $daughter_name = $eligible_daughters[0]->getCharacterName();
                            $daughter_id = $eligible_daughters[0]->getId();
                            $daughter_fam = $eligible_daughters[0]->getWhichFamily();
                        } else {
                            
                            $daughter_name = $eligible_daughters[1]->getCharacterName();
                            $daughter_id = $eligible_daughters[1]->getId();
                            $daughter_fam = $eligible_daughters[1]->getWhichFamily();
                        }

                    } else {
                        $rand = mt_rand(1,2);
                        if ($rand == '1') {
                            
                            $daughter_name = $eligible_daughters[0]->getCharacterName();
                            $daughter_id = $eligible_daughters[0]->getId();
                            $daughter_fam = $eligible_daughters[0]->getWhichFamily();
                        } else {
                            
                            $remaining_daughters = $daughter_count - 1;
                            $remaining_rand = mt_rand(1,$remaining_daughters);
                            
                            $daughter_name = $eligible_daughters[$remaining_rand]->getCharacterName();
                            $daughter_id = $eligible_daughters[$remaining_rand]->getId();
                            $daughter_fam = $eligible_daughters[$remaining_rand]->getWhichFamily();

                        }
                    }   //// end daughter_count IFs

                   

                    // who to marry?
                    $husband_rand = mt_rand(0,(count($eligible_husbands) - 1));
                   
                    echo "<br>It has been proposed that " . $daughter_name . " should marry " . $eligible_husbands[$husband_rand]->getCharacterName();
                    $husband_id = $eligible_husbands[$husband_rand]->getId();
                    $husband_fam = $eligible_husbands[$husband_rand]->getWhichFamily();

                    $daughter_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $daughter_id);
                    $hudband_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $husband_id);

                    $daughter_data->setMarriageCode('1');
                    $this->doctrine->em->persist($daughter_data);

                    $new_proposal = new ORM\Dynasties2\Proposals;

                    $new_proposal->setFromFamily($daughter_fam);
                    $new_proposal->setToFamily($husband_fam);
                    $new_proposal->setOnTurn($current_turn);
                    $new_proposal->setTimeStamp(new DateTime());
                    $new_proposal->setCharacter1($daughter_data);
                    $new_proposal->setCharacter2($hudband_data);
                    $new_proposal->setTargetTurn($current_turn + 2);
                    $new_proposal->setMoney('0');
                    $new_proposal->setWedding('1');
                    $new_proposal->setStatus('1');

                    $this->doctrine->em->persist($new_proposal);
                    $this->doctrine->em->flush();
            
            
        } /// end public function AI_select_daughter_and_husband()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function AI_seek_spouse() {
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber();   
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE (u.marriedDate IS NULL)
                        AND (u.deathDate IS NULL)
                        AND u.isRuler = '1' 
                        AND u.useAI = '1'
                        ");
            
            $eligible_bachelors = $query->getResult();
            foreach ($eligible_bachelors as $row) {
                //echo "</br>" . $row->getCharacterName() . $row->getId() . " is looking for a wife.";
                $years_old = ($current_turn - $row->getBornDate()) / 8;
                //echo $row->getName() . " ($years_old), ";
                if ($years_old < '60') {
                 
                } else {
                    // don't bother, old and tired?
                }
                
            }
            
            
        }    /// end public function seek_spouse()
////////////////////////////////////////////////////////////////////////////////////////////////
 
        
        public function AI_claim_title_v2() {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $claim_cost = '10';
            
            echo "<br>-------Claim Title V2-------------------------------------------------";
            
            // who MIGHT want to claim?
            
            // who can they claim from?
            // - eliminate themselves
            // - eliminate their vassals
            // - eliminate their lords
            // - eliminate their allies
            
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE u.isRuler = '1' 
                        AND u.useAI = '1'
                        AND u.deathDate IS NULL
                        ");
            
            $selected_characters = $query->getResult();
            
            foreach ($selected_characters as $row) {
                
                $character_id = $row->getId();
                $ambition = $row->getAmbition();
                $ambition_chance = $ambition / 3;
                $ambition_rand = mt_rand(1,100);
                
                
                // should check here to see if they can claim at all - right now it lets them spend the money, but then if they are landless, they don't claim anything.
                
                if ($ambition_chance > $ambition_rand) {
                    //echo $row->getCharacterName() . " is looking to claim a title.[" . $ambition_chance . "]</br>";
                    
                    if ($row->getMoney() >= $claim_cost) {
                        $rand = mt_rand(1,3);
                        if ($rand > '1') {
                            
                            // spend the money, try the claim.
                            
                            
                            $updated_money = $row->getMoney() - $claim_cost;
                            $row->setMoney($updated_money);
                            $this->doctrine->em->persist($row);
                            $this->doctrine->em->flush();
                            
                            // chance for fabrication to work
                            $fabrication = mt_rand(1,100);
                            if ($fabrication > '49') {


                                $my_id = $row->getId();

                                // which regions do they own?
                                $query = $this->doctrine->em->createQuery("SELECT u 
                                        FROM ORM\Dynasties2\Titles u 
                                        WHERE u.characterLink = $my_id
                                            ");

                                $owned_regions = $query->getResult();

                                $sqlstring = "SELECT u 
                                            FROM ORM\Dynasties2\Regionneighbors u ";

                                if ($owned_regions) {
                                    
                                    $myregions = array();
                                    foreach ($owned_regions as $key => $row) {
                                        $myregions[] = $row -> getRegionLink()->getId();
                                        //echo $key . "- " . $row -> getRegionLink()->getId() . ", ";



                                        if ($key == '0') {
                                            $val = $row -> getRegionLink()->getId();
                                            $sqlstring = $sqlstring . "WHERE u.whichRegion = '$val'";
                                        } else {
                                            $val = $row -> getRegionLink()->getId();
                                            $sqlstring = $sqlstring . " OR u.whichRegion = '$val'";
                                        }

                                    }
                                    echo "<br>"; 

                                    
                                    $query = $this->doctrine->em->createQuery("$sqlstring");

                                    $neighbors = array();
                                    $neighbor_data = $query->getResult();
                                    foreach ($neighbor_data as $row) {
                                        //echo $row->getNeighborRegion() . ", ";
                                        if (!in_array($row->getNeighborRegion(), $myregions)) {
                                            $neighbors[] = $row->getNeighborRegion();
                                            // the above code adds regions to $neighbors() array, which is regions that are okay to claim
                                            // 
                                        } else {
                                            //echo "<br>Removed a neighbor! " . $row->getNeighborRegion() . " test</br> ";
                                        }  
                                    }
                                    
                                    /// now pull regionIDs for our lords or our vassals regions, and remove them from $neighbors()
                                    // do I have any vassals?
                                    $query = $this->doctrine->em->createQuery("SELECT u 
                                            FROM ORM\Dynasties2\Titles u 
                                            WHERE u.vassalTo = $character_id
                                                ");

                                    $my_vassals = $query->getResult();
                                    $vassal_ids = array();
                                    if ($my_vassals) {
                                        foreach ($my_vassals as $row) {
                                            $vassal_ids[] = $row->getCharacterLink()->getId();
                                            echo "<br>Char $character_id has a vassal: id " . $row->getCharacterLink()->getId() . ", region " . $row->getRegionLink()->getId();
                                            if (in_array($row->getRegionLink()->getId(), $neighbors)) {
                                                
                                                $keys = array_keys($neighbors, $row->getRegionLink()->getId());
                                              
                                                foreach ($keys as $row) {
                                                    // remove this row from neighbors
                                                    unset($neighbors[$row]);
                                                    
                                                }
                                            }
                                        }
                                    }
                                    
                                    $query = $this->doctrine->em->createQuery("SELECT u 
                                            FROM ORM\Dynasties2\Titles u 
                                            WHERE u.vassalTo IS NOT NULL
                                            AND u.characterLink = $character_id
                                                ");

                                    $my_lords = $query->getResult();
                                    if ($my_lords) {
                                        foreach ($my_lords as $row) {
                                            //echo "<br>Char $character_id has a Lord: id " . $row->getVassalTo() . ", in region " . $row->getRegionLink()->getId();
                                            if (in_array($row->getRegionLink()->getId(), $neighbors)) {
                                               
                                                // find and remove those rows from the array.
                                                $keys = array_keys($neighbors, $row->getRegionLink()->getId());
                                              
                                                foreach ($keys as $row) {
                                                    // remove this row from neighbors
                                                    unset($neighbors[$row]);
                                                    
                                                }
                                            }
                                        }
                                    }
                                    

                                    if (empty($neighbors)) {
                                        $logmsg = new ORM\Dynasties2\Gamelog;
                                        $logmsg -> setOnTurn($current_turn);
                                        $logmsg -> setText("WARNING: During title check, the neighbors array was empty, characterID $character_id,");
                                        $logmsg -> setTimeStamp(new DateTime());
                                        $logmsg -> setMsgType('2');
                                        $this->doctrine->em->persist($logmsg);
                                    }
                                    
                                    
                                    // get the neighbors of the regions that they own
                                   
                                    $rand_key = array_rand($neighbors);
                                    //echo $neighbors[$rand_key];
                                    
                                    $region_claiming = $neighbors[$rand_key];
                                    $title_data = $this->doctrine->em->getRepository('ORM\Dynasties2\Titles')->findOneBy(array('regionLink' => $region_claiming));
                                    $title_id = $title_data->getId();
                                    
                                    
                                    $logmsg = new ORM\Dynasties2\Gamelog;
                                    $logmsg -> setOnTurn($current_turn);
                                    $logmsg -> setText("Title Claimed for region: $region_claiming, by char $my_id, title: $title_id");
                                    $logmsg -> setTimeStamp(new DateTime());
                                    $logmsg -> setMsgType('2');
                                    $this->doctrine->em->persist($logmsg);
                                    
                                    echo "<br>$character_id lays claim to region $region_claiming, title $title_id";
                                    //$title_id = $title_claiming->getId();
                                    $query = $this->doctrine->em->createQuery("SELECT u 
                                            FROM ORM\Dynasties2\Titles u 
                                            WHERE u.characterLink = $character_id
                                                AND u.id = $title_id
                                                ");
                                   
                                    // temporarily, AI will not claim a title that already has a claim against it.
                                    $existing_claim = $this->doctrine->em->getRepository('ORM\Dynasties2\Claims')->findOneBy(array('titleLink' => $title_id));
                                    //echo "<br>**check 2 ** </br>";
                                    $title_check = $query->getResult();
                                    //echo "<br>**check 3 ** </br>";
                                    if (is_null($title_check)) {
                                        //echo "<br>title check IS NULL</br>";
                                    } else {
                                        if (is_null($existing_claim)) {
                                            //echo "<br>title check is not null</br>";

                                            // commit claim
                                            $new_claim = new ORM\Dynasties2\Claims;

                                            $title_data = $this->doctrine->em->find('ORM\Dynasties2\Titles', $title_id);
                                            
                                            $character_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $character_id);

                                            $new_claim->setTitleLink($title_data);
                                            $new_claim->setCharacterLink($character_data);
                                            $new_claim->setInherhit('0');

                                            $this->doctrine->em->persist($new_claim);
                                            $this->doctrine->em->flush();

                                        } else {
                                            // title is already claimed by someone
                                        } // end check to see if there is already a claim,  TEMPORARY
                                    }
                                    
                            } /// end IF owned_regions 
                            else {
                                // ????????????
                            }
                               
                            } else {
                                // nothing, money is spent, no claim is fabricated
                            }
                            
                            
                        }
                    }
                    
                    
                }
                
            } //end foreach
            
            
        }    /// end public function AI_claim_title_v2()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        public function AI_claim_war() {
        
            // have defender call up available levies from vassals/lords
            // if they are not already involved in a wary, get their levies.
            // if they are - check each turn to see if their war is finished and then bring their levies in
            
             echo "<br>-------Warfare-----------------------------------------------------";
             $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Claims u 
                     WHERE u.pending != '1'
                     ");
            
            $existing_claims = $query->getResult();
            
            foreach ($existing_claims as $row) {
                
                $is_AI = $row->getCharacterLink()->getUseAi();
                //echo "this is an existing claim,   ";
                $war_chance = mt_rand(1,3);
                if ($war_chance < '2' AND $is_AI == '1') {
                    // make sure this char is not already involved in a war.
                    $char_id = $row->getCharacterLink()->getId();
                    $existing_war = $this->doctrine->em->getRepository('ORM\Dynasties2\Wars')->findOneBy(array('attacker' => $char_id));
                    // line below prevents unlanded nobles from going to wary, TEMPORARY
                    $has_land = $this->doctrine->em->getRepository('ORM\Dynasties2\Titles')->findOneBy(array('characterLink' => $char_id));
                    
                    if ($has_land AND is_null($existing_war)) {
                        //echo "<br>Test - no war exists.";
                        //print_r($row->getCharacterLink());
                        echo "<br>" . $row->getCharacterLink() -> getCharacterName() . " " . $row->getCharacterLink()->getId() . " has decided to march to war against " . $row->getTitleLink()->getCharacterLink()->getId();
                        $attacker = $row->getCharacterLink()->getId();
                        $defender = $row->getTitleLink()->getCharacterLink()->getId();
                        //echo $defender;
                        
                        $new_war = new ORM\Dynasties2\Wars;
        
                        $new_war -> setAttacker($attacker);
                        $new_war -> setDefender($defender);
                        $new_war -> setWarType('1');
                        $new_war -> setPercentage('0');
                        $new_war -> setWhichClaim($row->getId());
                        
                        $this->doctrine->em->persist($new_war);
                        $this->doctrine->em->flush();
                        
                        $new_war_participant = new ORM\Dynasties2\Warparticipants;
                        $new_war_participant -> setWarLink($new_war);
                        $new_war_participant -> setWhichSide($defender);
                        $new_war_participant -> setWhichCharacter($defender);
                        //$new_war_participant -> setWhichTitle();
                        $this->doctrine->em->persist($new_war_participant);
                        
                        $new_war_participant = new ORM\Dynasties2\Warparticipants;
                        $new_war_participant -> setWarLink($new_war);
                        $new_war_participant -> setWhichSide($attacker);
                        $new_war_participant -> setWhichCharacter($attacker);
                        //$new_war_participant -> setWhichTitle();
                        $this->doctrine->em->persist($new_war_participant);
                        
                        
                        
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("War declared, id " . $new_war->getId() . ", attacker $attacker, defender $defender, fighting over claim# " . $row->getId());
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        $this->doctrine->em->flush();
                        
                        $this->call_levies($attacker);
                        
                        
                        $query = $this->doctrine->em->createQuery("SELECT u 
                                FROM ORM\Dynasties2\Titles u 
                                WHERE u.vassalTo = $defender
                                    ");
                        $my_vassals = $query->getResult();
                        if ($my_vassals) {
                            foreach ($my_vassals as $row) {
                                // is this vassal in a war?
                            }
                        }

                        $query = $this->doctrine->em->createQuery("SELECT u 
                                FROM ORM\Dynasties2\Titles u 
                                WHERE u.vassalTo IS NOT NULL
                                AND u.characterLink = $defender
                                    ");
                        $my_lords = $query->getResult();
                        if ($my_lords) {
                            foreach ($my_lords as $row) {
                                // is this lord in a war?
                            }
                        }      
                                    
                        $this->call_levies($defender);
                        
                        $this->doctrine->em->flush();
                        
                    } else {
                        // do nothing, already attacking someone
                        //echo "<br>Test - war exists!";
                    }
                    
                }
            }
            
        
        }    /// end public function AI_claim_war()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function call_levies($which_character) {
            // this needs to be moved out of turn.php
            // for the time being, this function should create an army, callup levies from the character's region, and attach those soldiers
            //    plus the character to the army
            
            $existing_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $which_character));
            if (is_null($existing_army)) {
                
                $character_data = $this->doctrine->em->find('ORM\Dynasties2\Characters', $which_character);

                // create army and components
                $new_army = new ORM\Dynasties2\Armies;
        
                $new_army -> setControlledBy($which_character);

                $this->doctrine->em->persist($new_army);
                $this->doctrine->em->flush();
                                    
                $new_armyForce = new ORM\Dynasties2\Armyforces;
        
                $new_armyForce -> setattachedNoble($which_character);
                $new_armyForce -> setLeadership($character_data->getLeadership());
                $new_armyForce -> setArmyLink($new_army);

                $this->doctrine->em->persist($new_armyForce);
                
                $demense = $this->doctrine->em->getRepository('ORM\Dynasties2\Titles')->findBy(array('characterLink' => $which_character));
                foreach ($demense as $row) {
                    
                    //echo "<br>Returned one row from demense check</br>";
                    
                    $soldiers = $row->getRegionLink()->getAvailSoldiers();
                    $row->getRegionLink()->setAvailSoldiers('0');
                    if ($soldiers < '1') {
                        echo "<br><b>Error, a query in call_levies has returned 0 soldiers!!!</b></br>";
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("ERROR - A query in call_levies returned 0 soldiers, region " . $row->getRegionLink()->getId());
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('3');
                        $this->doctrine->em->persist($logmsg);
                    }
                    $from = $row->getRegionLink()->getId();
                    
                    $new_armyForce = new ORM\Dynasties2\Armyforces;
        
                    $new_armyForce -> setSoldiers($soldiers);
                    $new_armyForce -> setSoldiersFrom($from);
                    $new_armyForce -> setArmyLink($new_army);

                    $this->doctrine->em->persist($new_armyForce);
                    
                }
                
                
                $this->doctrine->em->flush();
                
            } else {
                // do nothing
            }
            
            
            
        }   /// end public function call_levies()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function conduct_warfare() {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            echo "<br>-------Warfare-----------------------------------------------------";
            $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Wars u 
                     ");
            
            $wars = $query->getResult();
            
            foreach ($wars as $row) {
                
                $chance_meeting = mt_rand(1,2);
                if ($chance_meeting == '1') {
                    //echo "<br>Army engagement.</br>";
                    $attacker_id = $row->getAttacker();
                    //echo $attacker_id;
                    $defender_id = $row->getDefender();
                    
                    $attacking_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $attacker_id));
                    $defending_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $defender_id));
                    
                    
                    if ($attacking_army) {
                        $attacking_army_id = $attacking_army -> getId();
                    } else {
                        echo "<br>****An error has occurred, attackID: " . gettype($attacker_id) . "[";
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("ERROR - function conduct_warfare, in code to pull army data.  Attacker ID " . $attacker_id . " does not seem to have an army.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('3');
                        $this->doctrine->em->persist($logmsg);
                        echo $attacker_id;
                        echo "]</br>";
                        print_r($attacking_army);
                        echo "<br>*****<br>";
                        $attacking_army2 = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $attacker_id));
                        print_r($attacking_army2);
                        echo "<br>Test end*******</br>";
                    }
                     if ($defending_army) {
                        // this should always hit!  something weird is going on though and it sometimes misses
                        $defending_army_id = $defending_army -> getId();
                    } else {
                        echo "<br>****An error has occurred, defenderID: " . gettype($defender_id) . "[";
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("ERROR - function conduct_warfare, line ~883 'Undefined variable: defending_army_2' in code to pull army data.  Defender ID " . $defender_id . " does not seem to have an army.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('3');
                        $this->doctrine->em->persist($logmsg);
                        echo $defender_id;
                        echo "]</br>";
                        print_r($defending_army);
                        echo "<br>*****<br>";
                        $defending_army2 = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $defender_id));
                        print_r($defending_army_2);
                        echo "<br>Test end*******</br>";
                    }
                    
                    
                    $query = $this->doctrine->em->createQuery("
                            SELECT u 
                            FROM ORM\Dynasties2\Armyforces u 
                            WHERE u.armyLink = $attacking_army_id
                        ");
            
                    $attacker_armyforces = $query->getResult();
                    
                    $total_attacking_soldiers = '0';
                    $attacker_highest_leadership = '0';
                    $attacker_units = '0';
                    foreach ($attacker_armyforces as $row2) {
                        $attacker_units++;
                        //print_r($row);
                        $leadership = $row2->getLeadership();
                        if ($leadership > $attacker_highest_leadership) {
                            $attacker_highest_leadership = $leadership;
                            $attacker_best_leader_id = $row2->getAttachedNoble();
                        }
                        $attacking_soldiers = $row2->getSoldiers();
                        $total_attacking_soldiers = $total_attacking_soldiers + $attacking_soldiers;
                    }
                    //echo "<br>Attacker army: soldiers: " . $total_attacking_soldiers . ", leadership: " . $attacker_highest_leadership . "</br>";
                    if ($total_attacking_soldiers > '99') {
                        
                    
                   
                    
                    
                        $query = $this->doctrine->em->createQuery("
                                SELECT u 
                                FROM ORM\Dynasties2\Armyforces u 
                                WHERE u.armyLink = $defending_army_id
                            ");

                        $defender_armyforces = $query->getResult();

                        $total_defending_soldiers = '0';
                        $defender_highest_leadership = '0';
                        $defender_units = '0';
                        foreach ($defender_armyforces as $row2) {
                            $defender_units++;
                            //print_r($row);
                            $leadership = $row2->getLeadership();
                            if ($leadership > $defender_highest_leadership) {
                                $defender_highest_leadership = $leadership;
                                $defender_best_leader_id = $row2->getAttachedNoble();
                            }
                            $defending_soldiers = $row2->getSoldiers();
                            $total_defending_soldiers = $total_defending_soldiers + $defending_soldiers;
                        }
                        //echo "Defender army: soldiers: " . $total_defending_soldiers . ", leadership: " . $defender_highest_leadership . "</br>";

                        //////// check for 0 soldiers?



                        // compare attacker and defender leadership

                        $leadership_diff = $attacker_highest_leadership - $defender_highest_leadership;
                        //echo $leadership_diff;
                        // positive value favors attacker, negative value favors defender

                        if ($leadership_diff > '99') {
                            $attacker_strength = $total_attacking_soldiers * 100;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '89') {
                            $attacker_strength = $total_attacking_soldiers * 50;
                            $defender_strength = $total_defending_soldiers * 1;
                        } elseif ($leadership_diff > '74') {
                            $attacker_strength = $total_attacking_soldiers * 8;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '49') {
                            $attacker_strength = $total_attacking_soldiers * 4;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '24') {
                            $attacker_strength = $total_attacking_soldiers * 2;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '9') {
                            $attacker_strength = $total_attacking_soldiers * 1.5;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '-1') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '-11') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 1;

                        } elseif ($leadership_diff > '-26') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 1.5;

                        } elseif ($leadership_diff > '-51') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 2;

                        } elseif ($leadership_diff > '-76') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 4;

                        } elseif ($leadership_diff > '-91') {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 8;

                        } else {
                            $attacker_strength = $total_attacking_soldiers * 1;
                            $defender_strength = $total_defending_soldiers * 50;

                        }

                        //echo "Attacker Strength: " . $attacker_strength . ", defender strength: " . $defender_strength;
                        $combat_calculation = $attacker_strength / $defender_strength;
                        //echo ", " . $combat_calculation . " - " . $row -> getId() . "</br>";


                        echo "<br>Battle!  War: " . $row->getId() . ", percentage " . $row->getPercentage() . "<br>Attacking Army $attacking_army_id with $attacker_units units, Leader $attacker_best_leader_id score $attacker_highest_leadership, soldiers $total_attacking_soldiers score $attacker_strength, <br>Defending Army $defending_army_id with $defender_units units, Leader $defender_best_leader_id score $defender_highest_leadership, soldiers $total_defending_soldiers score $defender_strength.  <br>Score difference of " . round($combat_calculation,3) . ",";

                        $attacker_loss = '0';
                        $defender_loss = '0';
                        if ($combat_calculation < 1.3 && $combat_calculation > 0.75) {
                            // pretty close, outcome is rather a tossup, but better leader may prevail
                            $rand = mt_rand(1,4);
                            if ($rand == '1') {
                                // attacker wins by luck and chance
                                echo "Attacker Victory!</br>";
                                $attacker_casualties = $this->casualty_calculator('30');
                                $defender_casualties = $this->casualty_calculator('-30');
                                //$attacker_armyforces -> get
                                foreach ($attacker_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $attacker_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                }
                                foreach ($defender_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $defender_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                }
                                $war_percent_change = '30';
                                // maybe capture a leader
                                $capture_chance = mt_rand (1,20);
                                if ($capture_chance < '2') {
                                    echo "<br>the defender's leader would have been captured if the code were compelted!</br>";
                                    $war_percent_change = '60';
                                }
                            } elseif ($rand == '2') {
                                // defender wins by luck and chance
                                    echo "Defender Victory!</br>";
                                    $attacker_casualties = $this->casualty_calculator('-30');
                                $defender_casualties = $this->casualty_calculator('30');
                                foreach ($attacker_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $attacker_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                    }
                                    foreach ($defender_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $defender_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                    }
                                    $war_percent_change = '-30';
                                    // maybe capture a leader
                                    $capture_chance = mt_rand (1,20);
                                    if ($capture_chance < '2') {
                                        echo "<br>the attacker's leader would have been captured if the code were compelted!</br>";
                                        $war_percent_change = '-60';
                                    }
                            } elseif ($rand > '2') {
                                // determine by leaderskill
                                if ($leadership_diff > '1') {
                                    // attacker win
                                    echo "Attacker Victory!</br>";
                                    $attacker_casualties = $this->casualty_calculator('30');
                                    $defender_casualties = $this->casualty_calculator('-30');
                                    foreach ($attacker_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $attacker_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                    }
                                    foreach ($defender_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $defender_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                    }
                                    $war_percent_change = '30';
                                    // maybe capture a leader
                                    $capture_chance = mt_rand (1,20);
                                    if ($capture_chance < '2') {
                                        echo "<br>the defender's leader would have been captured if the code were compelted!</br>";
                                        $war_percent_change = '60';
                                    }
                                } else {
                                    // defender win
                                    echo "Defender Victory!</br>";
                                    $attacker_casualties = $this->casualty_calculator('-30');
                                    $defender_casualties = $this->casualty_calculator('30');
                                    foreach ($attacker_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $attacker_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                    }
                                    foreach ($defender_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $defender_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                    }
                                    $war_percent_change = '-30';
                                    // maybe capture a leader
                                    $capture_chance = mt_rand (1,20);
                                    if ($capture_chance < '2') {
                                        echo "<br>the attacker's leader would have been captured if the code were compelted!</br>";
                                        $war_percent_change = '-60';
                                    }
                                }
                            }


                        } elseif ($combat_calculation >= 1.3) {
                            // odds in attacker favor
                            $rand = mt_rand (1,4);
                            if ($rand > '1') {
                                // attacker win
                                echo "Attacker Victory!</br>";
                                $attacker_casualties = $this->casualty_calculator('30');
                                $defender_casualties = $this->casualty_calculator('-30');
                                foreach ($attacker_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $attacker_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                }
                                foreach ($defender_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $defender_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                }
                                $war_percent_change = '30';
                                // maybe capture a leader
                                $capture_chance = mt_rand (1,10);
                                if ($capture_chance < '2') {
                                    echo "<br>the defender's leader would have been captured if the code were compelted!</br>";
                                    $war_percent_change = '60';
                                }

                            } else {
                                // defender win
                                echo "Defender Victory!</br>";
                                $attacker_casualties = $this->casualty_calculator('-30');
                                $defender_casualties = $this->casualty_calculator('30');
                                foreach ($attacker_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $attacker_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                    }
                                    foreach ($defender_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $defender_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                    }
                                $war_percent_change = '-30';
                                // maybe capture a leader
                                $capture_chance = mt_rand (1,10);
                                if ($capture_chance < '2') {
                                    echo "<br>the attacker's leader would have been captured if the code were compelted!</br>";
                                    $war_percent_change = '-60';
                                }

                            }
                        } elseif ($combat_calculation <= 0.75) {
                            // odds in defender favor
                            $rand = mt_rand (1,4);
                            if ($rand > '1') {
                                // defender win
                                echo "Defender Victory!</br>";
                                $attacker_casualties = $this->casualty_calculator('-30');
                                $defender_casualties = $this->casualty_calculator('30');
                                foreach ($attacker_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $attacker_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                    }
                                    foreach ($defender_armyforces as $row2) {
                                        $soldiers = $row2->getSoldiers();
                                        $soldiers2 = $soldiers * $defender_casualties;
                                        $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                    }
                                $war_percent_change = '-30';
                                // maybe capture a leader
                                $capture_chance = mt_rand (1,10);
                                if ($capture_chance < '2') {
                                    echo "<br>the attacker's leader would have been captured if the code were compelted!</br>";
                                    $war_percent_change = '-60';
                                }
                            } else {
                                // attacker win
                                echo "Attacker Victory!</br>";
                                $attacker_casualties = $this->casualty_calculator('30');
                                $defender_casualties = $this->casualty_calculator('-30');
                                foreach ($attacker_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $attacker_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $attacker_loss = $attacker_loss + $soldiers - $soldiers2;
                                }
                                foreach ($defender_armyforces as $row2) {
                                    $soldiers = $row2->getSoldiers();
                                    $soldiers2 = $soldiers * $defender_casualties;
                                    $row2->setSoldiers($soldiers2);
                                    $defender_loss = $defender_loss + $soldiers - $soldiers2;
                                }
                                $war_percent_change = '30';
                                // maybe capture a leader
                                $capture_chance = mt_rand (1,20);
                                if ($capture_chance < '2') {
                                    echo "<br>the defender's leader would have been captured if the code were compelted!</br>";
                                    $war_percent_change = '60';
                                }
                            }
                        }

                        echo "Losses in combat for attacker $attacker_loss, defender $defender_loss</br>";
                        // check for leader death
                        $death_chance = mt_rand(1,100);
                        if ($death_chance < '2') {
                            echo "<br>We would have killed a leader if there were code in place for it!</br>";
                        }

                        // update war percentage
                        $new_percentage = $row->getPercentage() + $war_percent_change;
                        
                        
                    } ////// end if $total_attacking_soldiers > 99
                    else {
                        $new_percentage = '-200';
                    }
                    $war_update = $row->setPercentage($new_percentage);
                    $this->doctrine->em->persist($war_update);
                    $this->doctrine->em->flush();
                    
                } else {
                    // forces did not engage one another this turn
                    //echo "<br>Two armies did not engage one another.</br>";
                }
                
                
            }
            
            
        }   /// end public function conduct_warfare()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        

        public function casualty_calculator($modifier) {
            
            $marker = mt_rand(1,100) - $modifier;
            //echo "<br>Marker: " . $marker;
            
            $adjustor1 = '0.' . mt_rand(1,5);
            $adjustor2 = '0.7' + $adjustor1;
            
            //echo $marker;
            //$test = mt_rand(0.985,0.995);
            //echo "<br>adjust: " .$adjustor2;
            
            if ($marker <= '0') {
                //echo "<br>Case 1";
                $math = '0';
                $casualties = '0.99';
            } elseif ($marker > '100') {
                //echo "<br>Case 2";
                $math = '40' * $adjustor2;
            } elseif ($marker > '90') {
                $math = '30' * $adjustor2;
                $casualties = '0.7';
            } elseif ($marker > '70') {    
                $math = '25' * $adjustor2;
            } elseif ($marker > '50') {  
                $math = '20' * $adjustor2;
            } elseif ($marker > '30') {    
                $math = '15' * $adjustor2;
            } elseif ($marker > '10') {
                $math = '10' * $adjustor2;
                if ($math < '10') $math = '0' . $math;
            } elseif ($marker > '0') {
                $math = '5' * $adjustor2;
                $math = '0' . $math;
            }
            
                $math2 = '0.' . $math;
                $casualties = '1' - $math2;
                
            //echo "<br>math: " . round($math2, 2);
            //echo "<br>casualties: $casualties";
            return $casualties;  // want this to be a number that can be directly
                                // multiplied against current forces, so 0.9, 0.6, etc, never > 1.
            
            
        }  /// end public function casualty_calculator()
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function gestation() {
            
            //include 'function_library.php';
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE u.deathDate IS NULL
                        AND u.isFemale = '1' 
                        AND (u.isPregnant IS NOT NULL 
                            OR u.isPregnant > '0')
                        AND u.pregnantTurnsLeft > '0'
                        ");
            
            $pregnancies = $query->getResult();
            
            // check for child death, mother death, and advance pregnancy.. or have a baby
            foreach ($pregnancies as $key => $row) {
                
                if ($row -> getPregnantTurnsLeft() > '1') {
                    
                    // baby might die
                    $miscarry_chance = rand(1,100);
                    if ($miscarry_chance == '1') {
                        // miscarriage
                        // send a message
                        
                        // remove pregnancy from character
                        $not_pregnant = $row -> setIsPregnant('0');
                        $not_pregnant = $row -> setPregnantTurnsLeft(NULL);
                        //$this->doctrine->em->persist($not_pregnant);
                        //$this->doctrine->em->flush();
                    }
                    
                    // mother and baby might die
                    
                    
                    // otherwise, turnsleft decreases by 1
                    $turns_left = $row -> getPregnantTurnsLeft();
                    $new_turns_left = $turns_left - 1;
                    $modify_turnsleft = $row -> setPregnantTurnsLeft($new_turns_left);
                    $this->doctrine->em->persist($modify_turnsleft);
                    $this->doctrine->em->flush();
                    
                } // end if pregnangturnsleft > 1
                else if ($row -> getPregnantTurnsLeft() == '1') {
                    
                    //echo "Turns Left == 1";
                    // so pregnantturnsleft are 1, time to have a baby, check for death and such
                    // complication?
                    $complication = rand (1,40);
                    
                    if ($complication == '1') {
                        // great place to assign a character trait of 'sickly' or similar
                        
                        $mother = rand (1,4);
                        $child = rand (1,4);
                        
                         
                    } // end of complication code 1 in 40
                    
                    // or birth!
                    $sex = rand(1,2);
                    
                    
                    if ($sex == '1') {
                        //boy
                        //$this->load->third_party/function_library();
                        //$this->load->add_package_path(APPPATH.'third_party/function_library/');
                        //$name = $this -> function_library -> generate_male_name();
                        //$name = $this -> call_function('generate_male_name');
                        //?????????????
                        $this->load->helper('character_helper');
                        $name = generate_male_name();
                        
                        $is_female = '0';
                    } else if ($sex == '2') {
                        // girl
                        $this->load->helper('character_helper');
                        $name = generate_female_name();
                        $is_female = '1';
                    }
                    
                    $character_data['name'] = $name;
                    $character_data['whichfamily'] = $row -> getWhichFamily();
                    $character_data['bornturn'] = $this_turn; /// generated way above
                    $character_data['deathturn'] = '0';  
                    $character_data['marriedturn'] = '0';  
                    $character_data['marriedto'] = '0';  
                    $character_data['isfemale'] = $is_female;
                    $character_data['fathersID'] = $row -> getIsPregnant();
                    $character_data['religion'] = '0';
                    $character_data['successionorder'] = '0';   ///  <-- very important! ?????
                    $character_data['mothersID'] = $row -> getId();

                    $this->load->model('setup_data_model');
                    $my_id = $this->setup_data_model->commit_new_character_to_db($character_data);
                    
                    
                    // flush pregnancy data from character (if still alive?)
                    $not_pregnant = $row -> setIsPregnant('0');
                    $not_pregnant = $row -> setPregnantTurnsLeft(NULL);
                    $this->doctrine->em->persist($not_pregnant);
                    $this->doctrine->em->flush();
                        
                } // end ELSE for pregnantturnsleft
                
                
            } // end foreach pregnancies
            
            // if u.pregnantTurnsLeft = 1 then its time to have a baby, or a stillbirth, or die.
            //  twins?
            
            
            
        }  // end function  gestation
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function check_deaths() {
            
             $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("select u 
                    from ORM\Dynasties2\Characters u 
                    WHERE u.deathDate IS NULL OR u.deathDate = '0'");
            
            $potential_deaths = $query->getResult();
            //\Doctrine\Common\Util\Debug::dump($potential_deaths);
            
            foreach ($potential_deaths as $key => $row) {
                //echo $row -> getName();
                $born_turn = $row -> getBornDate();
                $age_in_turns = $turn_now - $born_turn;
                $age_in_years = $age_in_turns / 8;
                //echo $age_in_years;
                
                $chance = rand (1,1000);
                
                if ($age_in_years > '1' && $age_in_years <= '70') {
                    // 0.5% chance per month
                    if ($chance < '100') {
                        // dead
                        echo "</br>" . $row -> getCharacterName() . " has died.</br>";
                        $this -> death_code($row -> getId());
                        // export this user ID to a death function and have it kill them and remove marriages and such.
                        //$death = $row -> setDeathDate($turn_now);
                        //$this->doctrine->em->persist($death);
                        //$this->doctrine->em->flush();
                    }
                } /// end if age > 30 and age < 45
                
            } // end foreach potential_deaths
            
            
        }//// end function check_deaths
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        public function death_code($deadID) {
            //echo $deadID;
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            // make sure they won't attend any events or get married etc.  no ones likes it when zombies show up.
            
            $dead_person = $this->doctrine->em->find('ORM\Dynasties2\Characters', $deadID);
            $death = $dead_person -> setDeathDate($turn_now);
            
            
            //$this->doctrine->em->persist($death);
            //$this->doctrine->em->flush();
            
            
            
        } /// end function death_code
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        public function tax_income() {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $this->load->helper('dynasties2_common');
            
            //print_r(get_a_rulers_regions('14281'));
            
            $query = $this->doctrine->em->createQuery("SELECT u 
                    FROM ORM\Dynasties2\Characters u 
                    WHERE u.deathDate IS NULL
                        AND u.isRuler = '1'
                        ");
            $result = $query->getResult();
            
            foreach ($result as $row) {
                $regions = get_a_rulers_regions($row->getId());
                
                if ($regions) {
                    //echo "<br>";
                    //print_r($regions);
                    $region_count = count($regions);
                    
                    if ($region_count < '3') {
                        $too_many_regions_mod = '1'; // '1' is good, it won't change the numbers!
                    } elseif ($region_count == '3') {
                        $too_many_regions_mod = '0.5';
                    } elseif ($region_count == '4') {
                        $too_many_regions_mod = '0.35';
                    } elseif ($region_count == '5') {
                        $too_many_regions_mod = '0.25';
                    } elseif ($region_count == '6') {
                        $too_many_regions_mod = '0.15';
                    } else {
                        $too_many_regions_mod = '0.01';
                    }
                    
                    foreach ($regions as $row2) {
                        $regiondata = $this->doctrine->em->find('ORM\Dynasties2\Regions', $row2);
                        $base_tax_income = $regiondata->getTaxIncome();
                        $loyalty = $regiondata->getLoyalty();
                        $base_income = '10';  // base income is considered income from this character's own holdings in the county, 
                                                 //not subject to loyalty modifiers (but possibly to infrasturcture!)
                        $loyalty_mod = "." . $loyalty;  // busted if loyalty is 100!!
                        $modified_income = (($loyalty_mod * $base_tax_income) + $base_income) * $too_many_regions_mod;
                        $current_money = $row->getMoney();
                        $row->setMoney($current_money + $modified_income);
                        $this->doctrine->em->persist($row);
                        
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Tax income: " . $row->getId() . ", income from region " . $row2 . ", after toomanyregionmod of " . $too_many_regions_mod . " is " . $modified_income);
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        //$this->doctrine->em->persist($logmsg);
                    }
                    $this->doctrine->em->flush();
                } else {
                    //echo "<br>No data.";
                    // do nothing
                }
                
            }
            
        }/// end function death_code
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        public function check_war_status() {
            
            $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Wars u 
                     ");
            
            $wars = $query->getResult();
            
            foreach ($wars as $row) {
                
                if ($row->getPercentage() > '74') {
                    echo "<br>The attacker " . $row -> getAttacker() . " has overwhelmed the defender " . $row -> getDefender() . "!</br>";
                    // attacker winning
                    $data['winner'] = '1';
                    $data['attacker'] = $row->getAttacker();
                    $data['defender'] = $row->getDefender();
                    $data['claim'] = $row->getWhichClaim();
                    
                    $this->resolve_claim_war($data);
                    
                } elseif ($row->getPercentage() < '-74') {
                    // defender winning
                    echo "<br>The defender " . $row -> getDefender() . " has overwhelmed the attacker " . $row -> getAttacker() . "!</br>";
                    $data['winner'] = '2';
                    $data['attacker'] = $row->getAttacker();
                    $data['defender'] = $row->getDefender();
                    $data['claim'] = $row->getWhichClaim();
                    
                    $this->resolve_claim_war($data);
                    
                }
                
                
            } /// end foreach wars as rows
            
            
        } /// end function check_war_status
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        public function resolve_claim_war($data) {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $winner = $data['winner'];
            $attacker = $data['attacker'];
            $defender = $data['defender'];
            $claim = $data['claim'];
            
            $claimdata = $this->doctrine->em->find('ORM\Dynasties2\Claims', $claim);
            //echo "<br>Troubleshooting: \$claim is $claim.</br>";
            //print_r($claimdata);
            $titledata = $claimdata->getTitleLink();
            $region_number = $titledata->getRegionLink()->getId();
            $claimant = $claimdata->getCharacterLink();
            //echo "<br>Test: " . $claimant -> getCharacterName();
            $defenderdata = $this->doctrine->em->find('ORM\Dynasties2\Characters', $defender);
            
            if ($winner == '1') {
                //attacker won, 
                //$claimant->getReputation();
                $new_prestige = $claimant->getPrestige() + 50;
                $claimant->setPrestige($new_prestige);
                $this->doctrine->em->persist($claimant);
                //remove title from defender,   // give title to attacker
                $titledata -> setCharacterLink($claimant);
                $this->doctrine->em->persist($titledata);
                // give defender a claim
                $new_claim = new ORM\Dynasties2\Claims;
                $new_claim->setTitleLink($titledata);
                $new_claim->setCharacterLink($defenderdata);
                $new_claim->setInherhit('0');
                //$this->doctrine->em->persist($new_claim);   // disabled until later
                
                $claimant_duchy = $this->doctrine->em->getRepository('ORM\Dynasties2\Duchies')->findOneBy(array('characterLink' => $claimant));
                if ($claimant_duchy) {
                    $new_duchyregion = new ORM\Dynasties2\Duchyregions;
                    $new_duchyregion->setWhichDuchy($claimant_duchy->getId());
                    $new_duchyregion->setWhichRegion($region_number);
                    $this->doctrine->em->persist($new_duchyregion);
                }
                
                $in_a_duchy = $this->doctrine->em->getRepository('ORM\Dynasties2\Duchyregions')->findOneBy(array('whichRegion' => $region_number));
                if ($in_a_duchy) {
                    // remove it.
                    $this->doctrine->em->remove($in_a_duchy);
                    // new code, untested really.  6/14/12
                }
                
                $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($current_turn);
                $logmsg -> setText("Victory for attackerID " . $attacker . " over defender " . $defender . ", claim  " . $claim . ".");
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('2');
                $this->doctrine->em->persist($logmsg);
                
                $this->doctrine->em->flush();
                
                
                
                

            } else {
                // defender won, remove claim, war, etc
                $new_prestige = $claimant->getPrestige() - 50;
                $claimant->setPrestige($new_prestige);
                $this->doctrine->em->persist($claimant);
                $defender_prestige = $defenderdata->getPrestige() + 50;
                $defenderdata->setPrestige($defender_prestige);
                $this->doctrine->em->persist($defenderdata);
                
                $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($current_turn);
                $logmsg -> setText("Victory for DefenderID " . $defender . " over attacker " . $attacker . ", claim  " . $claim . ".");
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('2');
                $this->doctrine->em->persist($logmsg);
                
            }
            
            // also remove claim, war, etc
                
                
                $this_war = $this->doctrine->em->getRepository('ORM\Dynasties2\Wars')->findOneBy(array('whichClaim' => $claim));
                $this_war_id = $this_war->getId();
                //$war_participants = $this->doctrine->em->getRepository('ORM\Dynasties2\Warparticipants')->findOneBy(array('whichCharacter' => $this_war_id));
                $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Warparticipants u 
                    WHERE u.warLink = $this_war_id
                     ");
                $war_participants = $query->getResult();
                foreach ($war_participants as $row) {
                    $this->doctrine->em->remove($row);
                }
                $this->doctrine->em->remove($this_war);
                
                
                $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($current_turn);
                $logmsg -> setText("Removing a war from the tables: warID: " . $this_war->getId() . " between " . $this_war->getAttacker() . ", and " . $this_war->getDefender() . ", over claim " . $this_war->getWhichClaim());
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('2');
                $this->doctrine->em->persist($logmsg);
                
                $this->doctrine->em->flush();
                
                ////////////////////////
                $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Wars u 
                    WHERE u.attacker = $defender
                        OR u.defender = $defender
                        ");
            
                $defender_other_primary = $query->getResult();
                
                $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Wars u 
                    WHERE u.attacker = $attacker
                        OR u.defender = $attacker
                        ");
            
                $attacker_other_primary = $query->getResult();
                
                // if one of the above PRIMARY variables gets data, that means that this character
                // is the primary participant still in a war, i.e., while they were attacking someone elses claim,
                // they were attacked, making them a defender.
                // they need to keep their army for now.
                
                // if not, their army can be deleted, and their forces moved to another army, if they
                // are needed in an ally/vassal/lord's war.
                
                ////////////////////////
                $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Warparticipants u 
                    WHERE u.whichCharacter = $defender
                        ");
            
                $defender_other_wars = $query->getResult();
                
                $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Warparticipants u 
                    WHERE u.whichCharacter = $attacker
                        ");
            
                $attacker_other_wars = $query->getResult();
                //print_r($other_wars);
                
                if ($attacker_other_primary OR $defender_other_primary) {
                    
                    if ($attacker_other_wars AND $defender_other_primary) {
                        // both are in other wars.  do nothing.
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Check for multiple wars confirmed: Attacker AND defender both involved in other wars. nothing additional removed.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        
                        // remove these armies?
                        
                        // except perhaps the claim...
                        
                        $this->doctrine->em->flush();
                    } elseif ($attacker_other_primary) {
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Check for multiple wars confirmed: Attacker confirmed, but defender is not.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        
                        $defending_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $defender));
                            
                        $defending_army_id = $defending_army -> getId();
                        
                        ///////////////////////////////////////////////
                        $query = $this->doctrine->em->createQuery("
                                SELECT u 
                                FROM ORM\Dynasties2\Armyforces u 
                                WHERE u.armyLink = $defending_army_id
                                    ");
                        $armyforces = $query->getResult();
                            
                        if ($defender_other_wars) {
                            // defender is needed in another war,
                            // move their armyforces from the current army into another
                            
                            foreach ($armyforces as $row2) {
                                $side = $defender_other_wars->getWhichSide();
                                $new_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $side));
                                $row2 -> setArmyLink($new_army);
                                
                                $logmsg = new ORM\Dynasties2\Gamelog;
                                $logmsg -> setOnTurn($current_turn);
                                $logmsg -> setText("Moving a defending armyforce from old army to new (armyID " . $new_army->getId() . ")");
                                $logmsg -> setTimeStamp(new DateTime());
                                $logmsg -> setMsgType('2');
                                $this->doctrine->em->persist($logmsg);
                                
                                $this->doctrine->em->persist($row2);
                            }
                            
                        } else {
                            /// remove defender's rows
                            
                            foreach ($armyforces as $row2) {

                                $logmsg = new ORM\Dynasties2\Gamelog;
                                $logmsg -> setOnTurn($current_turn);
                                $logmsg -> setText("Removing a row from defender's armyforces, " . $row2->getId());
                                $logmsg -> setTimeStamp(new DateTime());
                                $logmsg -> setMsgType('2');
                                $this->doctrine->em->persist($logmsg);
                                
                                $from_region = $row2->getSoldiersFrom();
                                if ($from_region) {
                                    $region_data = $this->doctrine->em->find('ORM\Dynasties2\Regions', $from_region);
                                    $regionlevies = $region_data->getAvailSoldiers();
                                    $maxregionlevies = $region_data->getMaxSoldiers();
                                    $returning_soldiers = $row2->getSoldiers();
                                    $regionlevies = $regionlevies + $returning_soldiers;
                                    if ($regionlevies > $maxregionlevies) $regionlevies = $maxregionlevies;
                                 }
                                
                                $this->doctrine->em->remove($row2);
                            }
                        }
                        ////////////////////////////////////////////////
                        
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Removing defending army of char " . $defending_army->getControlledBy());
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        $this->doctrine->em->remove($defending_army); 
                        
                        
                        
                        
                        $this->doctrine->em->flush();
                    } elseif ($defender_other_primary) {
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Check for multiple wars confirmed: Defender confirmed, but attacker is not..");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        
                        $attacking_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $attacker));
                            
                        $attacking_army_id = $attacking_army -> getId();
                        
                        ////////////////////////////////////////
                        
                        
                        ////////////////////////////////////////
                        
                        $query = $this->doctrine->em->createQuery("
                        SELECT u 
                        FROM ORM\Dynasties2\Armyforces u 
                        WHERE u.armyLink = $attacking_army_id
                            ");
                        $armyforces = $query->getResult();
                        
                        if ($attacker_other_wars) {
                            
                            // defender is needed in another war,
                            // move their armyforces from the current army into another
                            
                            foreach ($armyforces as $row2) {
                                $side = $attacker_other_wars->getWhichSide();
                                $new_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $side));
                                $row2 -> setArmyLink($new_army);
                                
                                $logmsg = new ORM\Dynasties2\Gamelog;
                                $logmsg -> setOnTurn($current_turn);
                                $logmsg -> setText("Moving an attacking armyforce from old army to new (armyID " . $new_army->getId() . ")");
                                $logmsg -> setTimeStamp(new DateTime());
                                $logmsg -> setMsgType('2');
                                $this->doctrine->em->persist($logmsg);
                                
                                $this->doctrine->em->persist($row2);
                            }
                            
                            
                        } else {
                            // remove attacker army forces
                        
                            foreach ($armyforces as $row2) {
                                $logmsg = new ORM\Dynasties2\Gamelog;
                                $logmsg -> setOnTurn($current_turn);
                                $logmsg -> setText("Removing a row from attacker armyforces, " . $row2->getId());
                                $logmsg -> setTimeStamp(new DateTime());
                                $logmsg -> setMsgType('2');
                                $this->doctrine->em->persist($logmsg);
                                
                                $from_region = $row2->getSoldiersFrom();
                                if ($from_region) {
                                    $region_data = $this->doctrine->em->find('ORM\Dynasties2\Regions', $from_region);
                                    $regionlevies = $region_data->getAvailSoldiers();
                                    $maxregionlevies = $region_data->getMaxSoldiers();
                                    $returning_soldiers = $row2->getSoldiers();
                                    $regionlevies = $regionlevies + $returning_soldiers;
                                    if ($regionlevies > $maxregionlevies) $regionlevies = $maxregionlevies;
                                 }
                                
                                
                                $this->doctrine->em->remove($row2);
                            }
                        }
                        
                        
                        ///////////////////////////////////
                        
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Removing attacking army of char " . $attacking_army->getControlledBy());
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('2');
                    $this->doctrine->em->persist($logmsg);
                    $this->doctrine->em->remove($attacking_army);
                        
                    
                        $this->doctrine->em->flush();
                    } else {
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("A problem has occurred while checking for other attacker or defender wars.");
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        $this->doctrine->em->flush();
                    }
                    
                    
                    ////////////////////////////////////////
                }   ////// end the start of the IF to check for other wars
                else {
                    // appears that neither combattant are involved in another war
                    
                    
                    $attacking_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $attacker));
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Removing the attacking army, " . $attacking_army -> getId() . ", controlled by " . $attacking_army->getControlledBy());
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('2');
                    $this->doctrine->em->persist($logmsg);
                    $this->doctrine->em->remove($attacking_army);

                    $defending_army = $this->doctrine->em->getRepository('ORM\Dynasties2\Armies')->findOneBy(array('controlledBy' => $defender));
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Removing the defending army, " . $defending_army -> getId() . ", controlled by " . $defending_army->getControlledBy());
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('2');
                    $this->doctrine->em->persist($logmsg);
                    $this->doctrine->em->remove($defending_army); 
                    
                    $attacking_army_id = $attacking_army -> getId();
                    $defending_army_id = $defending_army -> getId();



                    $query = $this->doctrine->em->createQuery("
                        SELECT u 
                        FROM ORM\Dynasties2\Armyforces u 
                        WHERE u.armyLink = $attacking_army_id
                            OR u.armyLink = $defending_army_id
                            ");
                    $armyforces = $query->getResult();
                    
                    foreach ($armyforces as $row) {
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Removing a row from armyforces, " . $row->getId());
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        
                        $from_region = $row->getSoldiersFrom();
                        if ($from_region) {
                            $region_data = $this->doctrine->em->find('ORM\Dynasties2\Regions', $from_region);
                            $regionlevies = $region_data->getAvailSoldiers();
                            $maxregionlevies = $region_data->getMaxSoldiers();
                            $returning_soldiers = $row->getSoldiers();
                            $regionlevies = $regionlevies + $returning_soldiers;
                            if ($regionlevies > $maxregionlevies) $regionlevies = $maxregionlevies;
                            }
                        
                        $this->doctrine->em->remove($row);
                    }
                    
                    /// remove all participants in this war
                    $query = $this->doctrine->em->createQuery("
                        SELECT u 
                        FROM ORM\Dynasties2\Warparticipants u 
                        WHERE u.warLink = $this_war_id
                            ");
                    $warparticipants = $query->getResult();
                    foreach ($warparticipants as $row) {
                        $logmsg = new ORM\Dynasties2\Gamelog;
                        $logmsg -> setOnTurn($current_turn);
                        $logmsg -> setText("Removing a row from warparticipants: " . $row->getId());
                        $logmsg -> setTimeStamp(new DateTime());
                        $logmsg -> setMsgType('2');
                        $this->doctrine->em->persist($logmsg);
                        $this->doctrine->em->remove($row);
                    }
                
                
                }  /// end of the else to 
                $logmsg = new ORM\Dynasties2\Gamelog;
                $logmsg -> setOnTurn($current_turn);
                $logmsg -> setText("Removing a claim, " . $claimdata->getId());
                $logmsg -> setTimeStamp(new DateTime());
                $logmsg -> setMsgType('2');
                $this->doctrine->em->persist($logmsg);
                $this->doctrine->em->remove($claimdata);
                $this->doctrine->em->flush();
                 
            
            
        }  /// end function resolve_claim_war
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function region_levies_replenish() {
            
            $query = $this->doctrine->em->createQuery("
                        SELECT u 
                        FROM ORM\Dynasties2\Regions u 
                            ");
                    $regions = $query->getResult();
                    
                    foreach ($regions as $row) {
                        
                        $avail_levies = $row->getAvailSoldiers();
                         $max_levies = $row->getMaxSoldiers();
                        
                        if ($avail_levies < $max_levies) {
                            $increase_by = '100';
                            $new_avail_levies = $avail_levies + $increase_by;
                            if ($new_avail_levies > $max_levies) {
                                $new_avail_levies = $max_levies;
                            }
                            $row->setAvailSoldiers($new_avail_levies);
                        }
                        
                    }
            
            
            
        }  /// end function resolve_claim_war
////////////////////////////////////////////////////////////////////////////////////////////////
        
        public function check_pending_claims() {
            
            $turndata = $this->doctrine->em->find('ORM\Dynasties2\Currentturn', '1');
            $current_turn = $turndata->getTurnNumber(); 
            
            $query = $this->doctrine->em->createQuery("
                    SELECT u 
                    FROM ORM\Dynasties2\Claims u 
                        WHERE u.pending = '1'
                        ");

            $pending_claims = $query->getResult();
            
            foreach ($pending_claims as $row) {
                
                $rand = mt_rand(1,2);
                
                if ($rand < '2') {
                    //claim success
                    $row->setPending('0');
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Pending Claim " . $row->getId() . " was successful.");
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('2');
                    $this->doctrine->em->persist($logmsg);
                    
                } else {
                    // claim fail
                    $logmsg = new ORM\Dynasties2\Gamelog;
                    $logmsg -> setOnTurn($current_turn);
                    $logmsg -> setText("Pending Claim " . $row->getId() . " did not succeed and was removed");
                    $logmsg -> setTimeStamp(new DateTime());
                    $logmsg -> setMsgType('2');
                    $this->doctrine->em->persist($logmsg);
                    
                    $this->doctrine->em->remove($row);
                    
                }
                
            }
            
            
        }  /// end function resolve_claim_war
////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        }  /// end class turn
////////////////////////////////////////////////////////////////////////////////////////////////
        
        }   //// end session security.  no code under this line
////////////////////////////////////////////////////////////////////////////////////////////////